package shop.user.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import shop.common.entity.User;
import shop.user.mapper.UserMapper;
import shop.user.service.UserService;

import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {


    @Override
    public String login(String username, String password) {
        LambdaQueryWrapper<User> wrapper = Wrappers.lambdaQuery(User.class).eq(User::getUsername, username)
                .eq(User::getPassword, password);
        User one = this.getOne(wrapper);

        if (ObjectUtils.isEmpty(one)) {
            throw new RuntimeException("用户名或密码错误");
        }


        return one.getId();
    }

    @Override
    public boolean exist(String username) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, username);
        User user = this.getOne(wrapper);
        return !ObjectUtils.isEmpty(user);
    }

    @Override
    public Page<User> list(User user, Integer pageNum, Integer pageSize) {
        LambdaQueryWrapper<User> wrapper = Wrappers.lambdaQuery(User.class)
                .eq(!ObjectUtils.isEmpty(user.getId()), User::getId, user.getId())
                .like(!ObjectUtils.isEmpty(user.getNickname()), User::getNickname, user.getNickname())
                .like(!ObjectUtils.isEmpty(user.getUsername()), User::getUsername, user.getUsername()) ;

        Page<User> page = new Page<>(pageNum, pageSize);
        this.page(page, wrapper);
        List<User> list = page.getRecords().stream()
                .map(item -> this.details(item.getId()))
                .collect(Collectors.toList());
        page.setRecords(list);
        return page;
    }

    @Override
    public User details(String id) {
        return baseMapper.selectById(id);
    }

    @Override
    public User getByUsername(String username) {
        LambdaQueryWrapper<User> wrapper = Wrappers.lambdaQuery(User.class).eq(User::getUsername, username);
        User user = baseMapper.selectOne(wrapper);
        return details(user.getId());
    }
}




